package com.hilog.orderservice.controller;

import com.hilog.common.Result;
import com.hilog.orderservice.feign.ProductFeignClient;
import org.apache.skywalking.apm.toolkit.trace.Trace;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 订单服务控制器
 */
@RestController
@RequestMapping("/order")
public class OrderController {

    private static final Logger log = LoggerFactory.getLogger(OrderController.class);

    @Autowired
    private ProductFeignClient productFeignClient;

    /**
     * 下单接口
     * @param productId 商品ID
     * @return 下单结果
     */
    @Trace(operationName = "createOrder")
    @GetMapping("/create/{productId}")
    public Result<Map<String, Object>> createOrder(@PathVariable("productId") String productId) {
        log.info("开始下单，商品ID: {}", productId);
        
        try {
            // 获取当前traceId
            String traceId = MDC.get("traceId");
            log.info("当前traceId: {}", traceId);
            
            // 通过Feign调用商品服务的购买接口（商品服务会调用支付服务）
            log.info("调用商品服务购买商品");
            Map<String, Object> productResult = productFeignClient.buyProduct(productId, traceId);
            log.info("商品服务返回结果: {}", productResult);
            if ((Integer) productResult.get("code") != 200) {
                log.error("商品服务购买失败，商品ID: {}", productId);
                throw new RuntimeException("商品服务购买失败");
            }
            // 创建订单
            String orderId = "ORDER_" + System.currentTimeMillis();
            log.info("创建订单，订单ID: {}", orderId);
            
            // 组装最终结果
            Map<String, Object> result = new HashMap<>();
            result.put("orderId", orderId);
            result.put("productId", productId);
            result.put("productInfo", productResult);
            result.put("status", "下单成功");
            result.put("message", "订单创建成功，商品购买成功，支付扣款成功");
            
            log.info("下单成功，订单ID: {}", orderId);
//            log.info("下单成功，traceId: {}", tid);
            return Result.success(result);
            
        } catch (Exception e) {
            log.error("下单失败，商品ID: {}", productId, e);
            return Result.error("下单失败: " + e.getMessage());
        }
    }

    /**
     * 健康检查接口
     */
    @GetMapping("/health")
    public Result<String> health() {
        return Result.success("订单服务运行正常");
    }
} 